#!/bin/bash

# Asurada SSO客户端功能测试脚本

echo "=========================================="
echo "    Asurada SSO 客户端功能测试"
echo "=========================================="

# 配置
CLIENT_URL="http://localhost:8081"
SSO_SERVER_URL="http://localhost:8080"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 测试函数
test_endpoint() {
    local url=$1
    local description=$2
    local expected_status=${3:-200}
    
    echo -n "测试 $description ... "
    
    if command -v curl &> /dev/null; then
        response=$(curl -s -o /dev/null -w "%{http_code}" "$url")
        if [ "$response" -eq "$expected_status" ]; then
            echo -e "${GREEN}✅ 通过${NC} (HTTP $response)"
        else
            echo -e "${RED}❌ 失败${NC} (HTTP $response, 期望 $expected_status)"
        fi
    else
        echo -e "${YELLOW}⚠️  跳过${NC} (未找到curl)"
    fi
}

test_json_endpoint() {
    local url=$1
    local description=$2
    local method=${3:-GET}
    local data=${4:-""}
    
    echo -n "测试 $description ... "
    
    if command -v curl &> /dev/null; then
        if [ "$method" = "POST" ] && [ -n "$data" ]; then
            response=$(curl -s -X POST -H "Content-Type: application/json" -d "$data" "$url")
        else
            response=$(curl -s "$url")
        fi
        
        if echo "$response" | grep -q '"code"'; then
            echo -e "${GREEN}✅ 通过${NC}"
            echo "   响应: $(echo "$response" | head -c 100)..."
        else
            echo -e "${RED}❌ 失败${NC}"
            echo "   响应: $response"
        fi
    else
        echo -e "${YELLOW}⚠️  跳过${NC} (未找到curl)"
    fi
}

echo "1. 检查服务状态"
echo "----------------------------------------"

# 检查SSO服务端
echo -n "检查SSO服务端状态 ... "
if command -v curl &> /dev/null; then
    if curl -s "$SSO_SERVER_URL/actuator/health" > /dev/null 2>&1; then
        echo -e "${GREEN}✅ 运行中${NC}"
    else
        echo -e "${RED}❌ 未运行${NC}"
        echo -e "${YELLOW}请先启动SSO服务端: http://localhost:8080${NC}"
    fi
else
    echo -e "${YELLOW}⚠️  无法检查${NC} (未找到curl)"
fi

# 检查客户端
echo -n "检查SSO客户端状态 ... "
if command -v curl &> /dev/null; then
    if curl -s "$CLIENT_URL" > /dev/null 2>&1; then
        echo -e "${GREEN}✅ 运行中${NC}"
    else
        echo -e "${RED}❌ 未运行${NC}"
        echo -e "${YELLOW}请先启动SSO客户端: ./start.sh${NC}"
        exit 1
    fi
else
    echo -e "${YELLOW}⚠️  无法检查${NC} (未找到curl)"
fi

echo ""
echo "2. 测试页面访问"
echo "----------------------------------------"

# 测试页面端点
test_endpoint "$CLIENT_URL/" "首页访问"
test_endpoint "$CLIENT_URL/login" "登录页面"
test_endpoint "$CLIENT_URL/protected" "受保护页面" "302"  # 应该重定向到登录页
test_endpoint "$CLIENT_URL/profile" "个人信息页面" "302"   # 应该重定向到登录页

echo ""
echo "3. 测试API端点"
echo "----------------------------------------"

# 测试API端点
test_json_endpoint "$CLIENT_URL/sso/check" "登录状态检查"

# 测试登录API（需要有效凭据）
echo -n "测试登录API ... "
if command -v curl &> /dev/null; then
    login_data='{"account":"testuser","password":"password123"}'
    response=$(curl -s -X POST -H "Content-Type: application/json" -d "$login_data" "$CLIENT_URL/sso/login")
    
    if echo "$response" | grep -q '"code"'; then
        code=$(echo "$response" | grep -o '"code":[0-9]*' | cut -d':' -f2)
        if [ "$code" = "200" ]; then
            echo -e "${GREEN}✅ 登录成功${NC}"
            
            # 提取令牌进行后续测试
            access_token=$(echo "$response" | grep -o '"accessToken":"[^"]*"' | cut -d'"' -f4)
            if [ -n "$access_token" ]; then
                echo "   获取到访问令牌: ${access_token:0:20}..."
                
                # 测试需要认证的API
                echo -n "测试用户信息API ... "
                user_info_response=$(curl -s -H "Authorization: Bearer $access_token" "$CLIENT_URL/sso/userinfo")
                if echo "$user_info_response" | grep -q '"username"'; then
                    echo -e "${GREEN}✅ 通过${NC}"
                else
                    echo -e "${RED}❌ 失败${NC}"
                fi
            fi
        else
            echo -e "${YELLOW}⚠️  登录失败${NC} (可能是测试凭据无效)"
            echo "   响应: $(echo "$response" | head -c 100)..."
        fi
    else
        echo -e "${RED}❌ 失败${NC}"
        echo "   响应: $response"
    fi
else
    echo -e "${YELLOW}⚠️  跳过${NC} (未找到curl)"
fi

echo ""
echo "4. 测试静态资源"
echo "----------------------------------------"

# 检查静态资源（如果有的话）
test_endpoint "$CLIENT_URL/favicon.ico" "网站图标" "404"  # 可能不存在，404是正常的

echo ""
echo "5. 性能测试"
echo "----------------------------------------"

if command -v curl &> /dev/null; then
    echo -n "测试首页响应时间 ... "
    start_time=$(date +%s%N)
    curl -s "$CLIENT_URL/" > /dev/null
    end_time=$(date +%s%N)
    duration=$(( (end_time - start_time) / 1000000 ))
    
    if [ $duration -lt 1000 ]; then
        echo -e "${GREEN}✅ 优秀${NC} (${duration}ms)"
    elif [ $duration -lt 3000 ]; then
        echo -e "${YELLOW}⚠️  一般${NC} (${duration}ms)"
    else
        echo -e "${RED}❌ 较慢${NC} (${duration}ms)"
    fi
else
    echo -e "${YELLOW}⚠️  跳过性能测试${NC} (未找到curl)"
fi

echo ""
echo "6. 配置检查"
echo "----------------------------------------"

echo -n "检查配置文件 ... "
if [ -f "src/main/resources/application.yml" ]; then
    echo -e "${GREEN}✅ 存在${NC}"
    
    # 检查关键配置项
    if grep -q "server:" src/main/resources/application.yml; then
        echo "   ✓ 服务器配置"
    fi
    if grep -q "sso:" src/main/resources/application.yml; then
        echo "   ✓ SSO配置"
    fi
    if grep -q "jwt:" src/main/resources/application.yml; then
        echo "   ✓ JWT配置"
    fi
    if grep -q "redis:" src/main/resources/application.yml; then
        echo "   ✓ Redis配置"
    fi
else
    echo -e "${RED}❌ 缺失${NC}"
fi

echo ""
echo "7. 依赖检查"
echo "----------------------------------------"

echo -n "检查pom.xml ... "
if [ -f "pom.xml" ]; then
    echo -e "${GREEN}✅ 存在${NC}"
    
    # 检查关键依赖
    if grep -q "spring-boot-starter-web" pom.xml; then
        echo "   ✓ Spring Boot Web"
    fi
    if grep -q "spring-boot-starter-thymeleaf" pom.xml; then
        echo "   ✓ Thymeleaf模板引擎"
    fi
    if grep -q "spring-boot-starter-data-redis" pom.xml; then
        echo "   ✓ Redis支持"
    fi
    if grep -q "jjwt" pom.xml; then
        echo "   ✓ JWT支持"
    fi
else
    echo -e "${RED}❌ 缺失${NC}"
fi

echo ""
echo "=========================================="
echo "测试完成！"
echo ""
echo "如果所有测试都通过，您可以："
echo "1. 访问首页: $CLIENT_URL"
echo "2. 尝试登录: $CLIENT_URL/login"
echo "3. 查看受保护页面: $CLIENT_URL/protected"
echo "4. 查看个人信息: $CLIENT_URL/profile"
echo ""
echo "测试用户凭据（如果SSO服务端有的话）："
echo "- 用户名: testuser"
echo "- 密码: password123"
echo "=========================================="